//
//  LBTwoPassFilter.mm
//  OpenGLGame
//
//  Created by Nguyen Cong Huy on 11/27/12.
//  Copyright (c) 2012 UIT. All rights reserved.
//

#include <iostream>
#include "LBTwoPassFilter.h"
#include "LBFramebuffer.h"
#include "LBTexture.h"
#include "LBGraphics.h"
#include "LBUtils.h"

LBTwoPassFilter::LBTwoPassFilter(){
    program2 = 0;
    texture2 = 0;
    framebuffer = 0;
}

void LBTwoPassFilter::init(char* vShaderStr1, char* fShaderStr1, char* vShaderStr2, char* fShaderStr2){
    LBFilter::init(vShaderStr1, fShaderStr1);
    
    LBGraphics* g = LBGraphics::getInstance();
    if(program2 != 0) DELETE_SAFELY(program2);
    
    if(vShaderStr2 == 0 && fShaderStr2 != 0){
        program2 = new LBProgram(g->getDefaultVShaderStr(), fShaderStr2);
    }
    else if(vShaderStr2 != 0 && fShaderStr2 == 0){
        program2 = new LBProgram(vShaderStr2, g->getDefaultFShaderStr());
    }
    else if(vShaderStr2 != 0 && fShaderStr2 != 0){
        program2 = new LBProgram(vShaderStr2, fShaderStr2);
    }
    
    LBGraphics::getInstance()->useProgram(program2);
    
    positionAttribute2 = program2->attributeIndex("position");
    texCoorAttribute2 = program2->attributeIndex("texCoor");
    textureUniform2 = program2->uniformIndex("texture");
    
    texture2 = 0;
    framebuffer = 0;
    
    LBGraphics::getInstance()->useProgram(program);
}

void LBTwoPassFilter::renderTexture(int x, int y, float scaleX, float scaleY){
    LBGraphics* g = LBGraphics::getInstance();
    
    if(texture2 == 0){
        printf("Please set texture2 before\n");
        return;
    }
    
    //render to texture2
    framebuffer->beginRenderToTexture();
    g->useProgram(program);
    texture->setLocationAndScale(x, y, scaleX, scaleY);
    texture->setAngle(0.0f);
    texture->render();
    
    fbo->beginRenderToTexture();
    g->useProgram(program2);
    texture2->setLocationAndScale(x, y, scaleX, scaleY);
    texture2->setAngle(0.0f);
    texture2->render();
}

void LBTwoPassFilter::setTexture(LBTexture* texture){
    this->texture = texture;
    
    if(
       outputTexture == 0
       || (outputTexture != 0 && texture != 0 && (texture->getWidth() != outputTexture->getWidth() || texture->getHeight() != outputTexture->getHeight()))
       ){
        
        DELETE_SAFELY(outputTexture);
        outputTexture = new LBTexture(texture->getWidth(), texture->getHeight());
        DELETE_SAFELY(fbo);
        fbo = new LBFramebuffer(outputTexture);
        
        DELETE_SAFELY(texture2);
        texture2 = new LBTexture(texture->getWidth(), texture->getHeight());
        DELETE_SAFELY(framebuffer);
        framebuffer = new LBFramebuffer(texture2);
        
        if(targetFilter != 0){
            targetFilter->setTexture(outputTexture);
        }
    }
}

LBTwoPassFilter::~LBTwoPassFilter(){
    DELETE_SAFELY(program2);
    DELETE_SAFELY(framebuffer);
    DELETE_SAFELY(texture2);
}